package com.yokead.system;

import cn.jiangzeyin.common.JsonMessage;
import com.yokead.common.interceptor.LoginInterceptor;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by jiangzeyin on 2017/2/23.
 */
@ControllerAdvice
public class AppExceptionHandler {
    /**
     * 全局异常
     *
     * @param session the req
     * @param e       the e
     * @return string
     * @throws Exception the exception
     */
    @ExceptionHandler(value = {Exception.class, InstantiationException.class, IllegalAccessException.class, NullPointerException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String all(HttpSession session, Exception e, HttpServletRequest request) {
        String userName = (String) session.getAttribute(LoginInterceptor.SESSION_NAME);
        SystemLog.LOG(LogType.CONTROL_ERROR).error("controller 严重异常" + userName + "  " + request.getRequestURI(), e);
        if (e.getMessage().startsWith("Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException")) {
            return JsonMessage.getString(901, "service error:file size");
        }
        return JsonMessage.getString(900, "service error");
    }

    @ExceptionHandler(MultipartException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public String handleAll(Throwable t) {
        // TODO do sth
        SystemLog.ERROR().error("上传异常", t);
        return JsonMessage.getString(900, "上传异常");
    }
}
